﻿using Cloud.Core.Response.WebChat.WxUser;
using Cloud.Core.Response;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Cloud.Core.Model;
using System.Threading.Tasks;
using System.Linq;
using Cloud.Core.Response.WxUser;
using Cloud.Core.Request.WebChat.WxUser;
using Cloud.Core.Model.Promotion;
using System;
using System.Collections.Generic;
using System.Text;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Polly;

namespace Cloud.Core.Controllers.WebChat
{
    [Route("api/wx/[controller]")]
    public class HomeController : ControllerBase
    {
        private readonly CloudDataBase _context;

        private static readonly Random random = new Random();

        public HomeController(CloudDataBase context)
        {
            _context = context;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("GetLifeHomeInfoAsync")]
        public async Task<JsonResponse<NewComerIndexInfoResponse>> GetLifeHomeInfoAsync(LifeHomeInfoRequest lifeHomeInfoRequest)
        {
            var banner = await _context.Banner.Where(t => t.Status == 1).
                 Select(t => new BannerResponse
                 {
                     Title = t.Title,
                     Description = t.Description,
                     Image_url = t.Image_url,
                     Link_url = t.Link_url
                 }).FirstOrDefaultAsync();

            var promotionsIds = _context.NewComerInterlocution.Where(t => t.openid == lifeHomeInfoRequest.openid && t.isRight==true).Select(t => t.PromotionsId);
            var promotionUsersIds = _context.Promotions.Where(t => promotionsIds.Contains(t.Id)).Select(t => t.PromotionUsersId);

            var listquery =  _context.PromotionUsers.Join(_context.Promotions, t => t.Id, t1 => t1.PromotionUsersId, (t, t1) => new PromotionUsersResponse
            {
                PromotionName = t.PromotionName,
                PromotionAddress = t.PromotionAddress,
                PromotionUserType = t.PromotionUserType,
                SiteInfoImgs = t.SiteInfoImgs,
                RealNameImgs = t.RealNameImgs,
                RealNameInfo = t.RealNameInfo,
                ContactNumber = t.ContactNumber,
                PromotionImgs = t.PromotionImgs,
                PromotionGroupId = t1.Id
            }).Where(t => promotionsIds.Contains(t.PromotionGroupId));
            if (lifeHomeInfoRequest.PromotionUserType!="-1")
            {
                listquery= listquery.Where(t => t.PromotionUserType== lifeHomeInfoRequest.PromotionUserType);
            }

            var PromotionUsers = await listquery.ToListAsync();
            return new JsonResponse<NewComerIndexInfoResponse>
            {
                Data = new NewComerIndexInfoResponse { bannerResponse = banner, promotionUsersResponses = PromotionUsers },
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };
        }



        /// <summary>
        /// 获取抽奖列表
        /// </summary>
        /// <param name="luckyDrawListRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetLuckyDrawListInfo")]
        public async Task<JsonResponse<LuckyDrawListResponse>> GetLuckyDrawListInfo(LuckyDrawListRequest luckyDrawListRequest)
        {

            var promotions = await _context.Promotions.Where(o => o.Id == luckyDrawListRequest.PromotionGroupId).FirstOrDefaultAsync();
            var PromotionUsers = await _context.PromotionUsers.Where(o => o.Id == promotions.PromotionUsersId).FirstOrDefaultAsync();
            if (promotions == null)
            {
                return new JsonResponse<LuckyDrawListResponse>
                {
                    Msg = "活动已结束",
                    Status = ResponseStatus.ParameterError
                };
            }

            var luckyDrawCashCoupon = await _context.LuckyDrawCoupon.Where(t => t.PromotionsId == promotions.Id && t.CouponCount > 0).ToListAsync();




            return new JsonResponse<LuckyDrawListResponse>
            {


                Msg = "获取成功",
                Status = ResponseStatus.Success,
                Data = new LuckyDrawListResponse
                {
                    PromotionsId = promotions.Id,
                    PromotionImgs = PromotionUsers.PromotionImgs,
                    luckyDrawCashes = luckyDrawCashCoupon

                }

            };
        }

        /// <summary>
        /// 获取用户获得奖券
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="LuckyDrawCouponType"> 现金券 1,红包 2, 商品 3, 折扣券 4</param>
        ///    /// <param name="PromotionUserType"> 商户类型</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetUserCouponBag")]
        public async Task<JsonResponse<List<UserCouponBagResponse>>> GetUserCouponBag(string OpenId, LuckyDrawCouponType LuckyDrawCouponType, string PromotionUserType)
        {
           var query = _context.UserCouponBag.Join(_context.PromotionUsers, t => t.PromotionUsersId, t1 => t1.Id, (t, t1) => new UserCouponBagResponse
           {



               Id=t.Id,
               OpenId=t.OpenId,

               PromotionUsersId=t.PromotionUsersId,
               PromotionsId=t.PromotionsId,
               CouponName=t.CouponName,
               CouponCode=t.CouponCode,
               ExpirationDate=t.ExpirationDate,
               LuckyDrawDate=t.LuckyDrawDate,

               CouponCount=t.CouponCount,

               CouponAmount=t.CouponAmount,
               PromotionUserType=t.PromotionUserType,
               LuckyDrawCouponType=t.LuckyDrawCouponType,
               PromotionAddress=t1.PromotionAddress,
               PromotionName=t1.PromotionName,
               Status=t.Status
    });
            if (!string.IsNullOrEmpty(PromotionUserType))
            {
                query =  query.Where(o => o.PromotionUserType == PromotionUserType);
            }
            var UserCouponBags = await query.Where(o =>o.Status==1&&  o.OpenId == OpenId && o.LuckyDrawCouponType== LuckyDrawCouponType ).ToListAsync();

            return new JsonResponse<List<UserCouponBagResponse>>
            {
                Msg = "获取成功",
                Status = ResponseStatus.Success,
                Data = UserCouponBags
            };

        }







        /// <summary>
        /// 修改banner的浏览量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("BannerViewCountUpdateAsync")]
        public async Task<JsonResponse<bool>> BannerViewCountUpdateAsync(ulong id)
        {
            var banner = await _context.Banner.Where(t => t.Status == 1 &&  t.Id==id && t.promotioncountRest>0).FirstOrDefaultAsync();
            if (banner!=null && banner.promotioncountRest>0)
            {
                banner.promotioncountRest -= 1;
                _context.Update(banner);
                await _context.SaveChangesAsync();
            }

            return new JsonResponse<bool>
            {
                Data = true,
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };
        }










        /// <summary>
        /// 获取用户获得奖券
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="LuckyDrawCouponType"> 现金券 1,红包 2, 商品 3, 折扣券 4</param>
        ///    /// <param name="CouponCode"> 奖券Code</param>
        /// <returns></returns>
        [HttpPost]
        [Route("CancelUserCoupon")]
        public async Task<JsonResponse<bool>> CancelUserCoupon(string OpenId, LuckyDrawCouponType LuckyDrawCouponType, string CouponCode)
        {



         var UserCoupon= await  _context.UserCouponBag.Where(t=> t.OpenId== OpenId && t.LuckyDrawCouponType == LuckyDrawCouponType && t.CouponCode== CouponCode).FirstOrDefaultAsync();



            if (UserCoupon == null)
            {
                 
                    return new JsonResponse<bool>
                    {   Data=false,
                        Msg = "编码不存在",
                        Status = ResponseStatus.ParameterError
                    };
                
            }

            if (UserCoupon.Status == 0)
            {

                return new JsonResponse<bool>
                {
                    Data = false,
                    Msg = "已核销 不允许重复操作",
                    Status = ResponseStatus.ParameterError
                };

            }

            UserCoupon.Status =0;

            _context.Set<UserCouponBag>().Update(UserCoupon);

            _context.SaveChanges();


            return new JsonResponse<bool>
            {
                Msg = "获取成功",
                Status = ResponseStatus.Success,
                Data = true
            };

        }


        /// <summary>
        /// 获取推广商户获奖名单
        /// </summary>
        /// <param name="OpenId"></param>
        /// <param name="LuckyDrawCouponType"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPromotionUserCouponBag")]
        public async Task<JsonResponse<List<UserCouponBag>>> GetPromotionUserCouponBag(ulong PromotionsId)
        {

            var UserCouponBags = await _context.UserCouponBag.Where(o => o.PromotionsId == PromotionsId ).ToListAsync();

            return new JsonResponse<List<UserCouponBag>>
            {
                Msg = "获取成功",
                Status = ResponseStatus.Success,
                Data = UserCouponBags
            };

        }
        /// <summary>
        /// 获取抽奖列表
        /// </summary>
        /// <param name="luckyDrawListRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LuckyDrawEvent")]
        public async Task<JsonResponse<bool>> LuckyDrawEvent(LuckyDrawEventRequest luckyDrawEventRequest)
        {


            var promotions = await _context.Promotions.Where(o => o.Id == luckyDrawEventRequest.PromotionId).FirstOrDefaultAsync();
            if (promotions == null)
            {
                return new JsonResponse<bool>
                {
                    Msg = "活动已结束",
                    Status = ResponseStatus.ParameterError
                };
            }

            var luckyDrawCashCoupons = await _context.LuckyDrawCoupon.Where(t => t.PromotionsId == promotions.Id && t.CouponCount > 0).ToListAsync();
            if (luckyDrawCashCoupons.Count <= 0)
            {
                return new JsonResponse<bool>
                {
                    Msg = "活动已结束",
                    Status = ResponseStatus.ParameterError
                };
            }

            var promotionsuser = await _context.PromotionUsers.Where(o => o.Id == promotions.PromotionUsersId).FirstOrDefaultAsync();
            int randomIndex = random.Next(luckyDrawCashCoupons.Count);
            var luckyDrawCashCoupon = luckyDrawCashCoupons[randomIndex];

            var usedCodes = new HashSet<string>();
            var code = GenerateUniqueCode();


            var userCouponBag = new UserCouponBag
            {
                OpenId = luckyDrawEventRequest.OpenId,
                PromotionsId = luckyDrawCashCoupon.PromotionsId,
                PromotionUsersId= promotionsuser.Id,
                CouponName = luckyDrawCashCoupon.CouponName,
                CouponCode = code,
                ExpirationDate = luckyDrawCashCoupon.LuckyDrawDate,
                LuckyDrawDate = luckyDrawCashCoupon.LuckyDrawDate,
                CouponCount= 1,
                CouponAmount = luckyDrawCashCoupon.CouponAmount,
                IsrtDt = DateTime.Now,
                LuckyDrawCouponType= luckyDrawCashCoupon.LuckyDrawCouponType,
                PromotionUserType= promotionsuser.PromotionUserType,
                Status=1

            };
            luckyDrawCashCoupon.CouponCount -= 1;


            _context.Set<UserCouponBag>().Add(userCouponBag);
           
            _context.Set<LuckyDrawCoupon>().Update(luckyDrawCashCoupon);

            _context.SaveChanges();

            return new JsonResponse<bool>
            {
                Msg = "操作成功",
                Status = ResponseStatus.Success,
                Data = true

            };
        }



        private static string GenerateUniqueCode()
        {
            var usedCodes = new HashSet<string>();
            var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            var sb = new StringBuilder(5);
            string code;
            do
            {
                sb.Clear(); // Clear the StringBuilder for reuseb   for (int i = 0; i < 5; i++)
                {
                    sb.Append(characters[random.Next(characters.Length)]); // Append a random character to StringBuilder
                }
                code = sb.ToString(); // Convert StringBuilder to string
            } while (!usedCodes.Add(code)); // Check for uniqueness and add to set if unique
            return code;
        }

    }
}
